<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="groupName" placeholder="请输入分组名称" clearable size="small" prefix-icon="el-icon-search"/>
        </div>
        <div class="body-container">
          <el-tree :data="filterdGroupOptions" :props="defaultProps" :expand-on-click-node="false"
                   :default-checked-keys="defaultCheckedKeys" ref="tree" node-key="id"
                   default-expand-all highlight-current @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <template>
                <div style="display: flex; justify-content: space-between; margin-right: 10px;"
                     @click="selectNode(data)">
                  <span
                    :title="node.label"
                    :class="{ highlighted: node.label === '0' }"
                    style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis; display: block; max-width: 110px;"
                  >{{ node.label }}</span>
                  <span style="display: flex; justify-content: flex-end;">
                    <el-button v-show="data.id !== '0'" type="text" size="mini" icon="el-icon-edit"
                               @click="() => handleEditGroup(data)">
                    </el-button>
                    <el-button v-show="data.id !== '0'" type="text" size="mini" icon="el-icon-delete" style="color:red;"
                               @click="() => handleDeleteGroup(node, data)">
                    </el-button>
                  </span>
                </div>
              </template>
            </span>
          </el-tree>
        </div>
        <el-button style="margin-bottom: 10px;width: 178px;" icon="el-icon-plus" size="mini"
                   v-hasPermi="['hawk-eye:service-config:add']"
                   @click="() => handleAddGroup()">
          新建分组
        </el-button>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="服务名" prop="serviceName">
            <el-input v-model="queryParams.serviceName" placeholder="中/英文服务名均可,支持模糊查询" clearable
                      style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="负责人" prop="chargeUserId">
            <el-select v-model="queryParams.chargeUserId" filterable clearable placeholder="负责人,选项支持模糊过滤"
                       style="width: 240px;"
                       @change="val => handleStoreQueryParams(storeChargeUserKey, val)"
                       @keyup.enter.native="handleQuery">
              <el-option :key="self.value" :label="self.label"
                         :value="self.value"></el-option>
              <el-option v-for="user in userOptions" :key="user.userId" :label="user.name"
                         :value="user.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="disenabled">
            <el-select v-model="queryParams.disenabled" placeholder="禁用后告警日志不再推送和记录" clearable style="width: 240px">
              <el-option v-for="dict in disenabledOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddService"
                       v-hasPermi="['hawk-eye:service-config:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-monitor"
              size="mini"
              @click="handleWebhook"
              v-hasPermi="['hawk-eye:webhook:add']"
            >webhook
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-s-order"
              size="mini"
              @click="handleTemplate"
              v-hasPermi="['hawk-eye:template:add']"
            >模板配置
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" style="color: red;" :disabled="multiple"
                       @click="handleDeleteService"
                       v-hasPermi="['hawk-eye:service-config:remove']">删除
            </el-button>
          </el-col>
          <div style="display: flex; justify-content: flex-end;">
            <el-link style="font-size: 13px;color: blue;" :underline="false" @click="handleDoc('service')">什么是告警配置？</el-link>
          </div>
        </el-row>

        <el-table v-loading="loading" :data="serviceDataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="服务名" align="center" prop="serviceName"
                           :formatter="(row, column, cellValue, index) =>
                       `${row.serviceCnName ? row.serviceCnName:'unknown'}(${row.serviceZnName ? row.serviceZnName:'unknown'})`"
                           :show-overflow-tooltip="true" width="230"/>
          <el-table-column label="负责人" align="center" key="chargeUserName" prop="chargeUserName"
                           show-overflow-tooltip/>
          <el-table-column label="降噪规则" align="center" key="denoiseRule" prop="denoiseRule" :formatter="(row, column, cellValue, index) => {
            let data = JSON.parse(cellValue);
            if (data.denoisePeriod == null || data.denoisePeriod <= 0){
              return `不进行降噪`
            }else {
             return `${data.denoisePeriod}分钟内,告警超过${data.denoiseCount}次,则静默${data.denoiseSilencePeriod}分钟`
            }
          }" show-overflow-tooltip width="280"/>
          <el-table-column label="升级阈值" align="center" key="upgradesCount" prop="upgradesCount" width="80"/>
          <el-table-column label="状态" align="center" key="disenabled">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.disenabled" :active-value=0 :inactive-value=1
                         @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateService(scope.row)"
                         v-hasPermi="['hawk-eye:service-config:edit']">{{scope.row.isDraft === 1 ? '编辑草稿': '编辑'}}
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" style="color: red;"
                         @click="handleDeleteService(scope.row)"
                         v-hasPermi="['hawk-eye:service-config:remove']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="new Number(total) > 0" :total="new Number(total)" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getServiceList"/>
      </el-col>
    </el-row>
    <!-- 添加或修改用户配置对话框 -->
    <service-modal-form ref="serviceModalForm" @submitted="getServiceList"/>
    <group-modal-form ref="groupModalForm" @submitted="getGroupTree"/>
    <webhook-drawer ref="webhookDrawer"/>
    <template-drawer ref="templateDrawer"/>
  </div>
</template>

<script>
  import {
    changeServiceStatus,
    groupTreeList,
    removeService,
    serviceDetail,
    serviceList,
    userListNotSelf
  } from "@/api/hawkeye/service";
  import {removeGroup} from "@/api/hawkeye/group";
  import Treeselect from "@riophae/vue-treeselect";
  import ServiceModalForm from "./modules/ServiceModalForm";
  import GroupModalForm from "./modules/GroupModalForm";
  import WebhookDrawer from "./modules/WebhookDrawer";
  import TemplateDrawer from "./modules/TemplateDrawer";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "ServiceConfig",
    components: {Treeselect, ServiceModalForm, GroupModalForm, WebhookDrawer, TemplateDrawer},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        isSelected: false, // 控制选中状态
        // 总条数
        total: 0,
        // 用户表格数据
        serviceDataList: null,
        // 弹出层标题
        title: "",
        // 分组选项
        groupOptions: [],
        userOptions: [],
        self: {label: '仅看自己', value: -1},
        filterdGroupOptions: [],
        // 是否显示弹出层
        open: false,
        // 分组名称
        groupName: undefined,

        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        disenabledOptions: [
          {
            label: "启用",
            value: 0
          }, {
            label: "禁用",
            value: 1
          }
        ],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "name"
        },
        defaultCheckedKeys: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          groupId: 0
        },
        storeChargeUserKey: 'hawkEye:service:storeChargeUserKey',
      };
    },
    watch: {
      // 根据名称筛选分组
      groupName(val) {
        if (!val) {
          this.filterdGroupOptions = this.groupOptions;
          return
        }
        this.filterdGroupOptions = this.groupOptions.filter(item => item.name.includes(val));
        // this.$refs.tree.filter(val);
      },
      groupOptions(val) {
        this.filterdGroupOptions = val
      }
    },
    created() {
      this.initQueryParams();
      this.getGroupTree();
      this.getUserList();
    },
    methods: {
      initQueryParams() {
        let userIdAsString = localStorage.getItem(this.storeChargeUserKey);
        if (userIdAsString) {
          try {
            this.$set(this.queryParams, 'chargeUserId', JSON.parse(userIdAsString))
          } catch (e) {
            localStorage.removeItem(this.storeChargeUserKey);
          }
        }
      },
      /**  */
      getServiceList() {
        this.loading = true;
        serviceList(this.queryParams).then(res => {
          this.serviceDataList = res.records;
          this.total = res.total;
        }).finally(() => {
          this.loading = false;
        });
      },
      getUserList() {
        userListNotSelf().then(res => {
          this.userOptions = res.data;
        })
      },
      /** 查询分组数据 */
      getGroupTree() {
        groupTreeList().then(response => {
          this.groupOptions = response.data;
          this.defaultCheckedKeys.push("0")
          this.getServiceList();
        });
      },
      handleStoreQueryParams(key, value) {
        if (value) {
          localStorage.setItem(key, JSON.stringify(value));
        } else {
          localStorage.removeItem(key);
        }
      },
      selectNode(data) {
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.groupId = data.id;
        this.handleQuery();
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.disenabled === 0 ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.serviceCnName + '"服务的告警监控吗？停用后将不再接收任何告警！').then(function () {
          return changeServiceStatus({id: row.id, disenabled: row.disenabled});
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.disenabled = row.disenabled === 0 ? 1 : 0;
          this.$modal.msgError(text + "失败,请稍后重试");
        });
      },
      handleAddGroup() {
        this.$refs.groupModalForm.open()
      },
      handleEditGroup(data) {
        this.$refs.groupModalForm.open(data)
      },
      handleDeleteGroup(node, data) {
        if (data.id === '0') {
          this.$modal.msgWarning("默认分组，不可删除");
          return;
        }
        this.$modal.confirm('确认要删除' + data.name + '"分组吗？').then(() => {
          return removeGroup(data.id);
        }).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getGroupTree();
        }).catch(() => {

        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getServiceList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.groupId = undefined;
        this.$refs.tree.setCurrentKey(null);
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      handleWebhook() {
        this.$refs.webhookDrawer.open();
      },
      handleTemplate() {
        this.$refs.templateDrawer.open();
      },
      /** 新增按钮操作 */
      handleAddService() {
        this.$refs.serviceModalForm.open();
      },
      /** 修改按钮操作 */
      handleUpdateService(row) {
        this.$refs.serviceModalForm.reset()
        const id = row.id || this.ids;
        serviceDetail(id).then(res => {
          this.$refs.serviceModalForm.open(res.data);
        });
      },
      /** 删除按钮操作 */
      handleDeleteService(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function () {
          return removeService(ids);
        }).then(() => {
          this.getServiceList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {

        });
      },
      handleDoc(){
        let url = 'https://www.wolai.com/mszzReNkVvaRqVTJpprWmx';
        if (!url) {
          return;
        }
        window.open(url);
      }
    }
  };
</script>
<style scoped>
  .head-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
  }

  .body-container {
    margin-bottom: 10px;
  }
</style>
